package com.xyy.saas.payment.callback.core.service.impl;

import com.xyy.saas.payment.callback.core.handler.JDCallbackHandler;
import com.xyy.saas.payment.callback.core.service.NotifyService;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.util.AssertUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author liujf
 */
@Slf4j
@Component
public class NotifyServiceImpl implements NotifyService, InitializingBean {
    @Autowired
    private ApplicationContext applicationContext;
    private Map<String, JDCallbackHandler> methodHandlerMap = new HashMap<>();

    @Override
    public void jdCallback(String ch, String method, HttpServletRequest request) throws Exception {
        JDCallbackHandler handler = methodHandlerMap.get(method);

        //参数校验
        AssertUtil.equals(Constants.JD_PAY_CHANNEL, ch, ch + "渠道错误");
        AssertUtil.notNull(handler, "无效的method：" + method);

        handler.callbackHandle(request);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, JDCallbackHandler> handlerMap = applicationContext.getBeansOfType(JDCallbackHandler.class);

        for (JDCallbackHandler handler : handlerMap.values()) {
            methodHandlerMap.put(handler.getMethod(), handler);
        }
    }
}
